package com.bos.action;

import java.io.IOException;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.bos.bean.Region;
import com.bos.bean.Subarea;
import com.bos.service.SubareaService;

@Controller
@Scope("prototype")
public class SubareaAction extends BaseAction<Subarea>{

	@Autowired
	private SubareaService service;
	
	private String decidedId;
	
	public String add(){
		//保存
		service.save(model);
		return LIST;
	}
	
	public String pageQuery() throws IOException{
		//根据  addressKey   省  市  区  模糊查询
		//获取 这些值
		//获取到criteria 的对象
		DetachedCriteria criteria = pageBean.getCriteria();
		String addressKey = model.getAddresskey();
		if(StringUtils.isNotBlank(addressKey)){
			//添加查询条件
			criteria.add(Restrictions.like("addressKey", "%" + addressKey + "%"));
		}
		
		Region region = model.getRegion();
		if(region != null){
			//创建一个别名  给region
			criteria.createAlias("region", "r");
			//判断
			String province = region.getProvince();
			if(StringUtils.isNotBlank(province)){
				criteria.add(Restrictions.like("r.province", "%" + province + "%"));
			}
			String city = region.getCity();
			if(StringUtils.isNotBlank(city)){
				criteria.add(Restrictions.like("r.city", "%" + city + "%"));
			}
			String district = region.getDistrict();
			if(StringUtils.isNotBlank(district)){
				criteria.add(Restrictions.like("r.district", "%" + district + "%"));
			}
		}
		service.pageQuery(pageBean);
		//java转JSON
		objToJson(pageBean,new String[]{ "currentPage", "pageSize", "criteria","subareas"});
		return NONE;
	}
	
	//查询没有被关联的分区
	public String querynorelevance() throws IOException{
		//1.查询所有的分区  然后 去除掉有  dicidedzone的  分区
		//2.查询的时候附带  decidedZone为空的条件
		List<Subarea> subareas = service.findNoRelevance();
		listToJSON(subareas, new String[]{"region"});
		return NONE;
	}
	
	public String getSubareaByDecidedId() throws IOException{
		//加上条件  根据定区id 查询分区
		DetachedCriteria criteria = pageBean.getCriteria();
		//根据定区ID查询分区
		criteria.add(Restrictions.eq("decidedZone.id", decidedId));
		service.pageQuery(pageBean);
		objToJson(pageBean,new String[]{ "currentPage", "pageSize", "criteria","subareas","decidedZone"});
		return NONE;
	}
	

	public String getDecidedId() {
		return decidedId;
	}

	public void setDecidedId(String decidedId) {
		this.decidedId = decidedId;
	}
	
	
}

